package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import domain.Distrito;
import domain.Queja;

public class JDBCDistritoDAO implements IDistritoDAO {
	private Connection conn;
	
	public JDBCDistritoDAO(){
		conn = ConnectionManager.getInstance().checkOut();
		System.out.println("SE HA CREADO LA CONEXION");
	}
	@Override
	public List<Distrito> selectAllDistritos() {
		// TODO Auto-generated method stub
		PreparedStatement stmt=null;
		ResultSet result=null;
		List<Distrito> searchResults=new LinkedList<Distrito>();
		
		String sql="SELECT * FROM distritos";
		
		try{
			stmt=conn.prepareStatement(sql);
			stmt.executeQuery();
			result=stmt.executeQuery();
			
			while(result.next()){
				
				Distrito d = new Distrito();
				d.setIdDistrito(result.getString("OIDDistrito"));
				d.setNombre(result.getString("nombre"));
				searchResults.add(d);
			}
				
			} catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
	            try {
	                if (result != null) {
	                    result.close();
	                }
	                if (stmt != null) {
	                    stmt.close();
	                }
	            } catch (SQLException e) {
	            }
	        }
		return searchResults;
	}
	
	public Distrito select(String idDistrito) {
		// TODO Auto-generated method stub
		PreparedStatement stmt = null;
        ResultSet result = null;
        Distrito d=null;
        
        try {

            String sql = "SELECT * FROM   distritos WHERE OIDDistrito = ?";
            stmt = conn.prepareStatement(sql); 
            stmt.setString(1, idDistrito);
            stmt.executeQuery();
            result = stmt.executeQuery();

            result.next();
            d = new Distrito();
            d.setNombre(result.getString("nombre"));
            
           
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally { 
            ConnectionManager.getInstance().checkIn(conn);
            System.out.println("SE HA CERRADO LA CONEXION");
            try {
                if (result != null)
                    result.close();
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
            }

        }
        return d;

	}


}
